package com.xdwanj.interceptor;

import com.alibaba.fastjson.JSON;
import com.xdwanj.common.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public boolean check(String[] urls, String uri) {
        for (String url : urls) {
            if (uri.startsWith(url)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        String[] urls = new String[]{
            "/css/",
            "/api/",
            "/js/",
            "/img/",
            "/view/",
            "/index.html",
            "/login.html",
            "/user",
        };
        String uri = request.getRequestURI();
        log.info("================URI:" + uri);

        // 判断是否属于放行url
        if (check(urls, uri) || "/".equals(uri)) {
            log.info("=================不需要登陆");
            // filterChain.doFilter(request, response);
            return true;
        }

        // 2.判断用户是否登陆
        if (request.getSession().getAttribute("user") != null) {
            log.info("==================用户已经登陆");
            // filterChain.doFilter(request, response);
            return true;
        }
        // 不属于放行，也没有登陆
        log.info("============未登录");
        response.getWriter().write(JSON.toJSONString(R.error(-1, "NOTLOGIN")));
        return false;
    }
}
